//
//  RequesetManager.m
//  片刻
//
//  Created by lanou3g on 15/6/4.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RequesetManager.h"

//网络请求类

@implementation RequesetManager
//初始化方法
-(instancetype)initWithRequestURL:(NSString *)urlString requestModel:(RequestModel)requstModel parameyer:(NSString *)parameyer
{
    self = [super init];
    if (self) {
        _requesParameyer = parameyer;
        _requestModel = requstModel;
        _requestURL = urlString;
        _parameyerDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}
//开启请求
-(void)startRequest
{
//    网络请求
    NSURL *url = [NSURL URLWithString:_requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (_requestModel == POST) {
       [request setHTTPMethod:@"POST"];
        [self parameterDictToString];
        [request setHTTPBody:[_requesParameyer dataUsingEncoding:NSUTF8StringEncoding]];
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}
//字典的字符串参数
-(void)parameterDictToString{
    if (_parameyerDict.count != 0) {
        NSMutableArray *arr = [NSMutableArray array]; //创建一个数组来存放
        for (NSString *key in _parameyerDict) {
//            用str存放字符
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameyerDict[key]];
            [arr addObject:str];
        }
        //这个方法会吧数组里的元素连接起来，以给的参数（&）来连接，最后形成一个字符串返回
        _requesParameyer = [arr componentsJoinedByString:@"&"];
    }
}

//拼接返回的data，此方法可能会多次执行
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//开始响应的方法，在这里对自己的data进行初始化
-  (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    self.data = [NSMutableData data];
}
//成功的时候
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinshWithData:)]) {
        [_delegate requestDidFinshWithData:self.data];
    }
}
//错误的时候
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        [_delegate requestError:error];
    }
}
-(void)dealloc
{
    [_data release];
    [super dealloc];
}
@end











